#ifndef KERNEL_P_H
#define KERNEL_P_H

#include <QtCore/QObject>
#include <QtCore/QSettings>
#include <QtCore/QFile>
#include <QtCore/QMutex>
#include <QtCore/QThread>
#include <QtCore/QRegExp>
#include <QtSql/QSqlDatabase>
#include "global.h"

namespace smsbilling {

class Kernel;

class KernelPrivate : public QObject {
  Q_OBJECT
public:
  KernelPrivate();

  ~KernelPrivate();

protected:

  void timerEvent(QTimerEvent *);

private slots:

  void threadStarted();

  void stop();

  void initServerExecuted();

  void initTariffsExecuted();

  void initResourcesExecuted();

  void syncDatabaseExecuted();

  void newBillingSession(binaryrpc::Session *session);

  void openSession();

  void closeSession();

  void errorSession(const QString &error_string);

  void newMessageSession(binaryrpc::ServerMessage *message);

  void syncDatabase();

signals:

  void sigStop();

private:

  bool readConfig(QSettings *config);

  void setState(State state);

  void initServer();

  void initTariffs();

  void initResources();

  void checkState();

  Tariff *getTariff(quint32 id) const;

  Resource *getResource(quint32 id) const;

  float getCostTariff(Tariff *tariff,
                      const QString &address,
                      quint32 num) const;

  float roundUp(float val, quint32 digits) const;

  friend class Kernel;

  smslog::LogLevel log_level;

  QString db_host;

  quint16 db_port;

  QString db_name;

  QString db_uname;

  QString db_pass;

  int num_connect_db;

  int exec_query_timeout;

  int sync_db_timer;

  QString last_error;

  binaryrpc::Server *billing_server;

  dbmanager::DatabaseManager *db_manager;

  QThread *thread;

  State state;

  QMutex mutex;

  KernelSettings *settings;

  QList<binaryrpc::Session *> sessions;

  QList<Tariff *> tariffs;

  QList<Resource *> resources;

  QHash<QString, QString> queries_to_debited;

  QString queries_to_resources_history;

  QList<dbmanager::SqlQuery *> queries;

  static const quint64 counter_life_int = Q_UINT64_C(2592000000);
};

} // namespace smsbilling

#endif // KERNEL_P_H
